﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WorkBasket.Api;
using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using Newtonsoft.Json;

namespace WorkBasket.Models
{
    public class FormModel
    {
        public Form Form { get; set; }
        private FormControl _RootControl;
        private SOC soc = new SOC(new MyContext());
        public FormControl RootControl
        {
            get {
                if (_RootControl == null)
                {
                    _RootControl = soc.FormControls.Where(c => c.FormID == Form.FormID && c.ParentControlID == 0).FirstOrDefault();
                }
                return _RootControl; 
            }
            set { _RootControl = value; }
        }
        public string GetHTML(){

            return RecursiveHTML(RootControl);
            

        }
        public Dictionary<string, string> InstanceData { get; set; }

        private string RecursiveHTML(FormControl ctl )
        {

            string sReturn= string.Empty;

            string prehtml = string.Empty;
            string posthtml = string.Empty;

            foreach (IControl ctlx in ExtensionsHost.Extensions.Controls)
            {
                if(ctlx.ControlName == ctl.ControlName)
                {

                    Instance instance = new Instance();


                    Dictionary<string, string> props = JsonConvert.DeserializeObject<Dictionary<string, string>>(ctl.Properties);
                    instance.Properties = props;
                  
                    instance.Data = InstanceData;

                    prehtml = ctlx.RenderBeginTag(instance);
                    posthtml = ctlx.RenderEndTag();
                }

            }

            sReturn += prehtml;

            //recursion
            IEnumerable<FormControl> ChildControls = soc.FormControls.Where(c => c.ParentControlID == ctl.FormControlID).ToList<FormControl>();


            foreach (FormControl child in ChildControls)
            {
                sReturn += RecursiveHTML(child);
            }

            sReturn += posthtml;
            return sReturn;

        }
        protected class Instance : IInstance
        {

            public Dictionary<string,string> Properties { get; set; }
            public Dictionary<string, string> Data { get; set; }
        }



        public  int InstanceID { get; set; }

        public  int StepID { get; set; }

        public  int WorkflowID { get; set; }

        public int ProcessVersionID { get; set; }
    }


}